package com.hfjava.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/doLogin02.action")
public class LoginServlet02 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String logId = request.getParameter("username");
        String logPwd = request.getParameter("password");
        String saveTime = request.getParameter("saveTime");
        HttpSession session = request.getSession(false);

        //登录成功
        if ("tomcat".equalsIgnoreCase(logId) && "123000".equals(logPwd)) {
            //保存当前用户状态
            session.setAttribute("user", logId);
            String userInfo = logId + "|" + logPwd;
            Cookie userCookie = new Cookie("userInfo", userInfo);
            userCookie.setHttpOnly(true);//防止Cookie劫持,禁止JS获取cookie
            response.addCookie(userCookie);
            if (saveTime.equals("having")) {
                userCookie.setMaxAge(0);
            } else if (saveTime.equals("oneDay")) {
                userCookie.setMaxAge(24 * 3600);
            } else if (saveTime.equals("oneWeek")) {
                userCookie.setMaxAge(24 * 3600 * 7);
            } else if (saveTime.equals("oneMonth")) {
                userCookie.setMaxAge(24 * 3600 * 30);
            }
            response.addCookie(userCookie);

            response.sendRedirect("home.jsp");

        } else {
            request.setAttribute("errmsg", "账号或密码输入错误，小老掉记性不中啊！");
            RequestDispatcher rd = request.getRequestDispatcher("login02.jsp");
            rd.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
